package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.excel.RiskdailyStockRepoSzAm;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.excel.RiskdailyStockRepoSzAmRepo;
import com.glsc.ngateway.opmanage.service.report.excel.ExcelUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class RiskdailyStockRepoSzAmListener extends AnalysisEventListener<RiskdailyStockRepoSzAm> {

    private static final Logger logger = LoggerFactory.getLogger(ExcelUploadService.class);
    private static final int BATCH_COUNT = 3000;
    List<RiskdailyStockRepoSzAm> list = new ArrayList<RiskdailyStockRepoSzAm>();

    private RiskdailyStockRepoSzAmRepo riskdailyStockRepoSzAmRepo;
    private Double scale;
    private Date date;

    public RiskdailyStockRepoSzAmListener() {
    }

    public RiskdailyStockRepoSzAmListener(RiskdailyStockRepoSzAmRepo riskdailyStockRepoSzAmRepo, Date date) {
        this.riskdailyStockRepoSzAmRepo = riskdailyStockRepoSzAmRepo;
        this.date = date;
    }

    @Override
    public void invoke(RiskdailyStockRepoSzAm data, AnalysisContext context) {
        // 发现存在脏数据，过滤
        // 过滤条件为：业务日期为空的数据
        if (null == data.getSource()) {
            return;
        }
        data.setDate(date);

        if (null != data.getScale()) {
            scale = data.getScale();
        } else {
            data.setScale(scale);
        }

        if (null != data.getSource() && !data.getSource().equals("合计")) {
            list.add(data);
        }

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        riskdailyStockRepoSzAmRepo.saveAll(list);
    }
}
